3 * Class for blocks stored in the database.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
23 namespace MediaWiki\Block
;
27 use BadMethodCallException
;
34 use MediaWiki\Block\Restriction\NamespaceRestriction
;
35 use MediaWiki\Block\Restriction\PageRestriction
;
36 use MediaWiki\Block\Restriction\Restriction
;
37 use MediaWiki\MediaWikiServices
;
44 use Wikimedia\Rdbms\Database
;
45 use Wikimedia\Rdbms\IDatabase
;
48 * A DatabaseBlock (unlike a SystemBlock) is stored in the database, may
49 * give rise to autoblocks and may be tracked with cookies. Such blocks
50 * are more customizable than system blocks: they may be hardblocks, and
51 * they may be sitewide or partial.
53 * @since 1.34 Renamed from Block.
55 class DatabaseBlock
extends AbstractBlock
{
60 public $mParentBlockId;
68 /** @var int Hack for foreign blocking (CentralAuth) */
69 private $forcedTargetID;
75 private $isAutoblocking;
77 /** @var Restriction[] */
78 private $restrictions;
81 * Create a new block with specified option parameters on a user, IP or IP range.
83 * @param array $options Parameters of the block:
84 * user int Override target user ID (for foreign users)
85 * auto bool Is this an automatic block?
86 * expiry string Timestamp of expiration of the block or 'infinity'
87 * anonOnly bool Only disallow anonymous actions
88 * createAccount bool Disallow creation of new accounts
89 * enableAutoblock bool Enable automatic blocking
90 * hideName bool Hide the target user name
91 * blockEmail bool Disallow sending emails
92 * allowUsertalk bool Allow the target to edit its own talk page
93 * sitewide bool Disallow editing all pages and all contribution
94 * actions, except those specifically allowed by
97 * @since 1.26 $options array
99 public function __construct( array $options = [] ) {
100 parent
::__construct( $options );
107 'createAccount' => false,
108 'enableAutoblock' => false,
110 'blockEmail' => false,
111 'allowUsertalk' => false,
115 $options +
= $defaults;
117 if ( $this->target
instanceof User
&& $options['user'] ) {
118 # Needed for foreign users
119 $this->forcedTargetID
= $options['user'];
122 $this->setExpiry( wfGetDB( DB_REPLICA
)->decodeExpiry( $options['expiry'] ) );
125 $this->mAuto
= (bool)$options['auto'];
126 $this->setHideName( (bool)$options['hideName'] );
127 $this->isHardblock( !$options['anonOnly'] );
128 $this->isAutoblocking( (bool)$options['enableAutoblock'] );
129 $this->isSitewide( (bool)$options['sitewide'] );
130 $this->isEmailBlocked( (bool)$options['blockEmail'] );
131 $this->isCreateAccountBlocked( (bool)$options['createAccount'] );
132 $this->isUsertalkEditAllowed( (bool)$options['allowUsertalk'] );
134 $this->mFromMaster
= false;
138 * Load a block from the block id.
140 * @param int $id id to search for
141 * @return DatabaseBlock|null
143 public static function newFromID( $id ) {
144 $dbr = wfGetDB( DB_REPLICA
);
145 $blockQuery = self
::getQueryInfo();
146 $res = $dbr->selectRow(
147 $blockQuery['tables'],
148 $blockQuery['fields'],
155 return self
::newFromRow( $res );
162 * Return the list of ipblocks fields that should be selected to create
164 * @deprecated since 1.31, use self::getQueryInfo() instead.
167 public static function selectFields() {
168 global $wgActorTableSchemaMigrationStage;
170 if ( $wgActorTableSchemaMigrationStage & SCHEMA_COMPAT_READ_NEW
) {
171 // If code is using this instead of self::getQueryInfo(), there's a
172 // decent chance it's going to try to directly access
173 // $row->ipb_by or $row->ipb_by_text and we can't give it
174 // useful values here once those aren't being used anymore.
175 throw new BadMethodCallException(
176 'Cannot use ' . __METHOD__
177 . ' when $wgActorTableSchemaMigrationStage has SCHEMA_COMPAT_READ_NEW'
181 wfDeprecated( __METHOD__
, '1.31' );
187 'ipb_by_actor' => 'NULL',
191 'ipb_create_account',
192 'ipb_enable_autoblock',
196 'ipb_allow_usertalk',
197 'ipb_parent_block_id',
199 ] + CommentStore
::getStore()->getFields( 'ipb_reason' );
203 * Return the tables, fields, and join conditions to be selected to create
204 * a new block object.
206 * @return array With three keys:
207 * - tables: (string[]) to include in the `$table` to `IDatabase->select()`
208 * - fields: (string[]) to include in the `$vars` to `IDatabase->select()`
209 * - joins: (array) to include in the `$join_conds` to `IDatabase->select()`
211 public static function getQueryInfo() {
212 $commentQuery = CommentStore
::getStore()->getJoin( 'ipb_reason' );
213 $actorQuery = ActorMigration
::newMigration()->getJoin( 'ipb_by' );
215 'tables' => [ 'ipblocks' ] +
$commentQuery['tables'] +
$actorQuery['tables'],
222 'ipb_create_account',
223 'ipb_enable_autoblock',
227 'ipb_allow_usertalk',
228 'ipb_parent_block_id',
230 ] +
$commentQuery['fields'] +
$actorQuery['fields'],
231 'joins' => $commentQuery['joins'] +
$actorQuery['joins'],
236 * Check if two blocks are effectively equal. Doesn't check irrelevant things like
237 * the blocking user or the block timestamp, only things which affect the blocked user
239 * @param DatabaseBlock $block
242 public function equals( DatabaseBlock
$block ) {
244 (string)$this->target
== (string)$block->target
245 && $this->type
== $block->type
246 && $this->mAuto
== $block->mAuto
247 && $this->isHardblock() == $block->isHardblock()
248 && $this->isCreateAccountBlocked() == $block->isCreateAccountBlocked()
249 && $this->getExpiry() == $block->getExpiry()
250 && $this->isAutoblocking() == $block->isAutoblocking()
251 && $this->getHideName() == $block->getHideName()
252 && $this->isEmailBlocked() == $block->isEmailBlocked()
253 && $this->isUsertalkEditAllowed() == $block->isUsertalkEditAllowed()
254 && $this->getReason() == $block->getReason()
255 && $this->isSitewide() == $block->isSitewide()
256 // DatabaseBlock::getRestrictions() may perform a database query, so
257 // keep it at the end.
258 && $this->getBlockRestrictionStore()->equals(
259 $this->getRestrictions(), $block->getRestrictions()
265 * Load blocks from the database which target the specific target exactly, or which cover the
268 * @param User|string|null $specificTarget
269 * @param int|null $specificType
270 * @param bool $fromMaster
271 * @param User|string|null $vagueTarget Also search for blocks affecting this target. Doesn't
272 * make any sense to use TYPE_AUTO / TYPE_ID here. Leave blank to skip IP lookups.
273 * @throws MWException
274 * @return DatabaseBlock[] Any relevant blocks
276 protected static function newLoad(
282 $db = wfGetDB( $fromMaster ? DB_MASTER
: DB_REPLICA
);
284 if ( $specificType !== null ) {
286 'ipb_address' => [ (string)$specificTarget ],
289 $conds = [ 'ipb_address' => [] ];
292 # Be aware that the != '' check is explicit, since empty values will be
293 # passed by some callers (T31116)
294 if ( $vagueTarget != '' ) {
295 list( $target, $type ) = self
::parseTarget( $vagueTarget );
297 case self
::TYPE_USER
:
298 # Slightly weird, but who are we to argue?
299 $conds['ipb_address'][] = (string)$target;
303 $conds['ipb_address'][] = (string)$target;
304 $conds[] = self
::getRangeCond( IP
::toHex( $target ) );
305 $conds = $db->makeList( $conds, LIST_OR
);
308 case self
::TYPE_RANGE
:
309 list( $start, $end ) = IP
::parseRange( $target );
310 $conds['ipb_address'][] = (string)$target;
311 $conds[] = self
::getRangeCond( $start, $end );
312 $conds = $db->makeList( $conds, LIST_OR
);
316 throw new MWException( "Tried to load block with invalid type" );
320 $blockQuery = self
::getQueryInfo();
322 $blockQuery['tables'], $blockQuery['fields'], $conds, __METHOD__
, [], $blockQuery['joins']
328 foreach ( $res as $row ) {
329 $block = self
::newFromRow( $row );
331 # Don't use expired blocks
332 if ( $block->isExpired() ) {
336 # Don't use anon only blocks on users
337 if ( $specificType == self
::TYPE_USER
&& !$block->isHardblock() ) {
341 // Check for duplicate autoblocks
342 if ( $block->getType() === self
::TYPE_AUTO
) {
343 $autoBlocks[] = $block;
346 $blockIds[] = $block->getId();
350 // Only add autoblocks that aren't duplicates
351 foreach ( $autoBlocks as $block ) {
352 if ( !in_array( $block->mParentBlockId
, $blockIds ) ) {
361 * Choose the most specific block from some combination of user, IP and IP range
362 * blocks. Decreasing order of specificity: user > IP > narrower IP range > wider IP
363 * range. A range that encompasses one IP address is ranked equally to a singe IP.
365 * Note that DatabaseBlock::chooseBlocks chooses blocks in a different way.
367 * This is refactored out from DatabaseBlock::newLoad.
369 * @param DatabaseBlock[] $blocks These should not include autoblocks or ID blocks
370 * @return DatabaseBlock|null The block with the most specific target
372 protected static function chooseMostSpecificBlock( array $blocks ) {
373 if ( count( $blocks ) === 1 ) {
377 # This result could contain a block on the user, a block on the IP, and a russian-doll
378 # set of rangeblocks. We want to choose the most specific one, so keep a leader board.
381 # Lower will be better
382 $bestBlockScore = 100;
383 foreach ( $blocks as $block ) {
384 if ( $block->getType() == self
::TYPE_RANGE
) {
385 # This is the number of bits that are allowed to vary in the block, give
386 # or take some floating point errors
387 $target = $block->getTarget();
388 $max = IP
::isIPv6( $target ) ?
128 : 32;
389 list( $network, $bits ) = IP
::parseCIDR( $target );
390 $size = $max - $bits;
392 # Rank a range block covering a single IP equally with a single-IP block
393 $score = self
::TYPE_RANGE
- 1 +
( $size / $max );
396 $score = $block->getType();
399 if ( $score < $bestBlockScore ) {
400 $bestBlockScore = $score;
409 * Get a set of SQL conditions which will select rangeblocks encompassing a given range
410 * @param string $start Hexadecimal IP representation
411 * @param string|null $end Hexadecimal IP representation, or null to use $start = $end
414 public static function getRangeCond( $start, $end = null ) {
415 if ( $end === null ) {
418 # Per T16634, we want to include relevant active rangeblocks; for
419 # rangeblocks, we want to include larger ranges which enclose the given
420 # range. We know that all blocks must be smaller than $wgBlockCIDRLimit,
421 # so we can improve performance by filtering on a LIKE clause
422 $chunk = self
::getIpFragment( $start );
423 $dbr = wfGetDB( DB_REPLICA
);
424 $like = $dbr->buildLike( $chunk, $dbr->anyString() );
426 # Fairly hard to make a malicious SQL statement out of hex characters,
427 # but stranger things have happened...
428 $safeStart = $dbr->addQuotes( $start );
429 $safeEnd = $dbr->addQuotes( $end );
431 return $dbr->makeList(
433 "ipb_range_start $like",
434 "ipb_range_start <= $safeStart",
435 "ipb_range_end >= $safeEnd",
442 * Get the component of an IP address which is certain to be the same between an IP
443 * address and a rangeblock containing that IP address.
444 * @param string $hex Hexadecimal IP representation
447 protected static function getIpFragment( $hex ) {
448 global $wgBlockCIDRLimit;
449 if ( substr( $hex, 0, 3 ) == 'v6-' ) {
450 return 'v6-' . substr( substr( $hex, 3 ), 0, floor( $wgBlockCIDRLimit['IPv6'] / 4 ) );
452 return substr( $hex, 0, floor( $wgBlockCIDRLimit['IPv4'] / 4 ) );
457 * Given a database row from the ipblocks table, initialize
459 * @param stdClass $row A row from the ipblocks table
461 protected function initFromRow( $row ) {
462 $this->setTarget( $row->ipb_address
);
463 $this->setBlocker( User
::newFromAnyId(
464 $row->ipb_by
, $row->ipb_by_text
, $row->ipb_by_actor ??
null
467 $this->setTimestamp( wfTimestamp( TS_MW
, $row->ipb_timestamp
) );
468 $this->mAuto
= $row->ipb_auto
;
469 $this->setHideName( $row->ipb_deleted
);
470 $this->mId
= (int)$row->ipb_id
;
471 $this->mParentBlockId
= $row->ipb_parent_block_id
;
473 // I wish I didn't have to do this
474 $db = wfGetDB( DB_REPLICA
);
475 $this->setExpiry( $db->decodeExpiry( $row->ipb_expiry
) );
477 CommentStore
::getStore()
478 // Legacy because $row may have come from self::selectFields()
479 ->getCommentLegacy( $db, 'ipb_reason', $row )->text
482 $this->isHardblock( !$row->ipb_anon_only
);
483 $this->isAutoblocking( $row->ipb_enable_autoblock
);
484 $this->isSitewide( (bool)$row->ipb_sitewide
);
486 $this->isCreateAccountBlocked( $row->ipb_create_account
);
487 $this->isEmailBlocked( $row->ipb_block_email
);
488 $this->isUsertalkEditAllowed( $row->ipb_allow_usertalk
);
492 * Create a new DatabaseBlock object from a database row
493 * @param stdClass $row Row from the ipblocks table
494 * @return DatabaseBlock
496 public static function newFromRow( $row ) {
497 $block = new DatabaseBlock
;
498 $block->initFromRow( $row );
503 * Delete the row from the IP blocks table.
505 * @throws MWException
508 public function delete() {
509 if ( wfReadOnly() ) {
513 if ( !$this->getId() ) {
514 throw new MWException(
515 __METHOD__
. " requires that the mId member be filled\n"
519 $dbw = wfGetDB( DB_MASTER
);
521 $this->getBlockRestrictionStore()->deleteByParentBlockId( $this->getId() );
522 $dbw->delete( 'ipblocks', [ 'ipb_parent_block_id' => $this->getId() ], __METHOD__
);
524 $this->getBlockRestrictionStore()->deleteByBlockId( $this->getId() );
525 $dbw->delete( 'ipblocks', [ 'ipb_id' => $this->getId() ], __METHOD__
);
527 return $dbw->affectedRows() > 0;
531 * Insert a block into the block table. Will fail if there is a conflicting
532 * block (same name and options) already in the database.
534 * @param IDatabase|null $dbw If you have one available
535 * @return bool|array False on failure, assoc array on success:
536 * ('id' => block ID, 'autoIds' => array of autoblock IDs)
538 public function insert( IDatabase
$dbw = null ) {
539 global $wgBlockDisablesLogin;
541 if ( !$this->getBlocker() ||
$this->getBlocker()->getName() === '' ) {
542 throw new MWException( 'Cannot insert a block without a blocker set' );
545 wfDebug( __METHOD__
. "; timestamp {$this->mTimestamp}\n" );
547 if ( $dbw === null ) {
548 $dbw = wfGetDB( DB_MASTER
);
551 self
::purgeExpired();
553 $row = $this->getDatabaseArray( $dbw );
555 $dbw->insert( 'ipblocks', $row, __METHOD__
, [ 'IGNORE' ] );
556 $affected = $dbw->affectedRows();
558 $this->setId( $dbw->insertId() );
559 if ( $this->restrictions
) {
560 $this->getBlockRestrictionStore()->insert( $this->restrictions
);
564 # Don't collide with expired blocks.
565 # Do this after trying to insert to avoid locking.
567 # T96428: The ipb_address index uses a prefix on a field, so
568 # use a standard SELECT + DELETE to avoid annoying gap locks.
569 $ids = $dbw->selectFieldValues( 'ipblocks',
572 'ipb_address' => $row['ipb_address'],
573 'ipb_user' => $row['ipb_user'],
574 'ipb_expiry < ' . $dbw->addQuotes( $dbw->timestamp() )
579 $dbw->delete( 'ipblocks', [ 'ipb_id' => $ids ], __METHOD__
);
580 $this->getBlockRestrictionStore()->deleteByBlockId( $ids );
581 $dbw->insert( 'ipblocks', $row, __METHOD__
, [ 'IGNORE' ] );
582 $affected = $dbw->affectedRows();
583 $this->setId( $dbw->insertId() );
584 if ( $this->restrictions
) {
585 $this->getBlockRestrictionStore()->insert( $this->restrictions
);
591 $auto_ipd_ids = $this->doRetroactiveAutoblock();
593 if ( $wgBlockDisablesLogin && $this->target
instanceof User
) {
594 // Change user login token to force them to be logged out.
595 $this->target
->setToken();
596 $this->target
->saveSettings();
599 return [ 'id' => $this->mId
, 'autoIds' => $auto_ipd_ids ];
606 * Update a block in the DB with new parameters.
607 * The ID field needs to be loaded first.
609 * @return bool|array False on failure, array on success:
610 * ('id' => block ID, 'autoIds' => array of autoblock IDs)
612 public function update() {
613 wfDebug( __METHOD__
. "; timestamp {$this->mTimestamp}\n" );
614 $dbw = wfGetDB( DB_MASTER
);
616 $dbw->startAtomic( __METHOD__
);
618 $result = $dbw->update(
620 $this->getDatabaseArray( $dbw ),
621 [ 'ipb_id' => $this->getId() ],
625 // Only update the restrictions if they have been modified.
626 if ( $this->restrictions
!== null ) {
627 // An empty array should remove all of the restrictions.
628 if ( empty( $this->restrictions
) ) {
629 $success = $this->getBlockRestrictionStore()->deleteByBlockId( $this->getId() );
631 $success = $this->getBlockRestrictionStore()->update( $this->restrictions
);
633 // Update the result. The first false is the result, otherwise, true.
634 $result = $result && $success;
637 if ( $this->isAutoblocking() ) {
638 // update corresponding autoblock(s) (T50813)
641 $this->getAutoblockUpdateArray( $dbw ),
642 [ 'ipb_parent_block_id' => $this->getId() ],
646 // Only update the restrictions if they have been modified.
647 if ( $this->restrictions
!== null ) {
648 $this->getBlockRestrictionStore()->updateByParentBlockId( $this->getId(), $this->restrictions
);
651 // autoblock no longer required, delete corresponding autoblock(s)
652 $this->getBlockRestrictionStore()->deleteByParentBlockId( $this->getId() );
655 [ 'ipb_parent_block_id' => $this->getId() ],
660 $dbw->endAtomic( __METHOD__
);
663 $auto_ipd_ids = $this->doRetroactiveAutoblock();
664 return [ 'id' => $this->mId
, 'autoIds' => $auto_ipd_ids ];
671 * Get an array suitable for passing to $dbw->insert() or $dbw->update()
672 * @param IDatabase $dbw
675 protected function getDatabaseArray( IDatabase
$dbw ) {
676 $expiry = $dbw->encodeExpiry( $this->getExpiry() );
678 if ( $this->forcedTargetID
) {
679 $uid = $this->forcedTargetID
;
681 $uid = $this->target
instanceof User ?
$this->target
->getId() : 0;
685 'ipb_address' => (string)$this->target
,
687 'ipb_timestamp' => $dbw->timestamp( $this->getTimestamp() ),
688 'ipb_auto' => $this->mAuto
,
689 'ipb_anon_only' => !$this->isHardblock(),
690 'ipb_create_account' => $this->isCreateAccountBlocked(),
691 'ipb_enable_autoblock' => $this->isAutoblocking(),
692 'ipb_expiry' => $expiry,
693 'ipb_range_start' => $this->getRangeStart(),
694 'ipb_range_end' => $this->getRangeEnd(),
695 'ipb_deleted' => intval( $this->getHideName() ), // typecast required for SQLite
696 'ipb_block_email' => $this->isEmailBlocked(),
697 'ipb_allow_usertalk' => $this->isUsertalkEditAllowed(),
698 'ipb_parent_block_id' => $this->mParentBlockId
,
699 'ipb_sitewide' => $this->isSitewide(),
700 ] + CommentStore
::getStore()->insert( $dbw, 'ipb_reason', $this->getReason() )
701 + ActorMigration
::newMigration()->getInsertValues( $dbw, 'ipb_by', $this->getBlocker() );
707 * @param IDatabase $dbw
710 protected function getAutoblockUpdateArray( IDatabase
$dbw ) {
712 'ipb_create_account' => $this->isCreateAccountBlocked(),
713 'ipb_deleted' => (int)$this->getHideName(), // typecast required for SQLite
714 'ipb_allow_usertalk' => $this->isUsertalkEditAllowed(),
715 'ipb_sitewide' => $this->isSitewide(),
716 ] + CommentStore
::getStore()->insert( $dbw, 'ipb_reason', $this->getReason() )
717 + ActorMigration
::newMigration()->getInsertValues( $dbw, 'ipb_by', $this->getBlocker() );
721 * Retroactively autoblocks the last IP used by the user (if it is a user)
722 * blocked by this block.
724 * @return array IDs of retroactive autoblocks made
726 protected function doRetroactiveAutoblock() {
728 # If autoblock is enabled, autoblock the LAST IP(s) used
729 if ( $this->isAutoblocking() && $this->getType() == self
::TYPE_USER
) {
730 wfDebug( "Doing retroactive autoblocks for " . $this->getTarget() . "\n" );
732 $continue = Hooks
::run(
733 'PerformRetroactiveAutoblock', [ $this, &$blockIds ] );
736 self
::defaultRetroactiveAutoblock( $this, $blockIds );
743 * Retroactively autoblocks the last IP used by the user (if it is a user)
744 * blocked by this block. This will use the recentchanges table.
746 * @param DatabaseBlock $block
747 * @param array &$blockIds
749 protected static function defaultRetroactiveAutoblock( DatabaseBlock
$block, array &$blockIds ) {
752 // No IPs are in recentchanges table, so nothing to select
753 if ( !$wgPutIPinRC ) {
757 // Autoblocks only apply to TYPE_USER
758 if ( $block->getType() !== self
::TYPE_USER
) {
761 $target = $block->getTarget(); // TYPE_USER => always a User object
763 $dbr = wfGetDB( DB_REPLICA
);
764 $rcQuery = ActorMigration
::newMigration()->getWhere( $dbr, 'rc_user', $target, false );
766 $options = [ 'ORDER BY' => 'rc_timestamp DESC' ];
768 // Just the last IP used.
769 $options['LIMIT'] = 1;
772 [ 'recentchanges' ] +
$rcQuery['tables'],
780 if ( !$res->numRows() ) {
781 # No results, don't autoblock anything
782 wfDebug( "No IP found to retroactively autoblock\n" );
784 foreach ( $res as $row ) {
786 $id = $block->doAutoblock( $row->rc_ip
);
796 * Checks whether a given IP is on the autoblock whitelist.
797 * TODO: this probably belongs somewhere else, but not sure where...
799 * @param string $ip The IP to check
802 public static function isWhitelistedFromAutoblocks( $ip ) {
803 // Try to get the autoblock_whitelist from the cache, as it's faster
804 // than getting the msg raw and explode()'ing it.
805 $cache = MediaWikiServices
::getInstance()->getMainWANObjectCache();
806 $lines = $cache->getWithSetCallback(
807 $cache->makeKey( 'ip-autoblock', 'whitelist' ),
809 function ( $curValue, &$ttl, array &$setOpts ) {
810 $setOpts +
= Database
::getCacheSetOptions( wfGetDB( DB_REPLICA
) );
812 return explode( "\n",
813 wfMessage( 'autoblock_whitelist' )->inContentLanguage()->plain() );
817 wfDebug( "Checking the autoblock whitelist..\n" );
819 foreach ( $lines as $line ) {
821 if ( substr( $line, 0, 1 ) !== '*' ) {
825 $wlEntry = substr( $line, 1 );
826 $wlEntry = trim( $wlEntry );
828 wfDebug( "Checking $ip against $wlEntry..." );
830 # Is the IP in this range?
831 if ( IP
::isInRange( $ip, $wlEntry ) ) {
832 wfDebug( " IP $ip matches $wlEntry, not autoblocking\n" );
835 wfDebug( " No match\n" );
843 * Autoblocks the given IP, referring to this block.
845 * @param string $autoblockIP The IP to autoblock.
846 * @return int|bool ID if an autoblock was inserted, false if not.
848 public function doAutoblock( $autoblockIP ) {
849 # If autoblocks are disabled, go away.
850 if ( !$this->isAutoblocking() ) {
854 # Check for presence on the autoblock whitelist.
855 if ( self
::isWhitelistedFromAutoblocks( $autoblockIP ) ) {
859 // Avoid PHP 7.1 warning of passing $this by reference
861 # Allow hooks to cancel the autoblock.
862 if ( !Hooks
::run( 'AbortAutoblock', [ $autoblockIP, &$block ] ) ) {
863 wfDebug( "Autoblock aborted by hook.\n" );
867 # It's okay to autoblock. Go ahead and insert/update the block...
869 # Do not add a *new* block if the IP is already blocked.
870 $ipblock = self
::newFromTarget( $autoblockIP );
872 # Check if the block is an autoblock and would exceed the user block
873 # if renewed. If so, do nothing, otherwise prolong the block time...
874 if ( $ipblock->mAuto
&& // @todo Why not compare $ipblock->mExpiry?
875 $this->getExpiry() > self
::getAutoblockExpiry( $ipblock->getTimestamp() )
877 # Reset block timestamp to now and its expiry to
878 # $wgAutoblockExpiry in the future
879 $ipblock->updateTimestamp();
884 # Make a new block object with the desired properties.
885 $autoblock = new DatabaseBlock
;
886 wfDebug( "Autoblocking {$this->getTarget()}@" . $autoblockIP . "\n" );
887 $autoblock->setTarget( $autoblockIP );
888 $autoblock->setBlocker( $this->getBlocker() );
889 $autoblock->setReason(
890 wfMessage( 'autoblocker', $this->getTarget(), $this->getReason() )
891 ->inContentLanguage()->plain()
893 $timestamp = wfTimestampNow();
894 $autoblock->setTimestamp( $timestamp );
895 $autoblock->mAuto
= 1;
896 $autoblock->isCreateAccountBlocked( $this->isCreateAccountBlocked() );
897 # Continue suppressing the name if needed
898 $autoblock->setHideName( $this->getHideName() );
899 $autoblock->isUsertalkEditAllowed( $this->isUsertalkEditAllowed() );
900 $autoblock->mParentBlockId
= $this->mId
;
901 $autoblock->isSitewide( $this->isSitewide() );
902 $autoblock->setRestrictions( $this->getRestrictions() );
904 if ( $this->getExpiry() == 'infinity' ) {
905 # Original block was indefinite, start an autoblock now
906 $autoblock->setExpiry( self
::getAutoblockExpiry( $timestamp ) );
908 # If the user is already blocked with an expiry date, we don't
909 # want to pile on top of that.
910 $autoblock->setExpiry( min( $this->getExpiry(), self
::getAutoblockExpiry( $timestamp ) ) );
913 # Insert the block...
914 $status = $autoblock->insert();
921 * Check if a block has expired. Delete it if it is.
924 public function deleteIfExpired() {
925 if ( $this->isExpired() ) {
926 wfDebug( __METHOD__
. " -- deleting\n" );
930 wfDebug( __METHOD__
. " -- not expired\n" );
938 * Has the block expired?
941 public function isExpired() {
942 $timestamp = wfTimestampNow();
943 wfDebug( __METHOD__
. " checking current " . $timestamp . " vs $this->mExpiry\n" );
945 if ( !$this->getExpiry() ) {
948 return $timestamp > $this->getExpiry();
953 * Is the block address valid (i.e. not a null string?)
955 * @deprecated since 1.33 No longer needed in core.
958 public function isValid() {
959 wfDeprecated( __METHOD__
, '1.33' );
960 return $this->getTarget() != null;
964 * Update the timestamp on autoblocks.
966 public function updateTimestamp() {
967 if ( $this->mAuto
) {
968 $this->setTimestamp( wfTimestamp() );
969 $this->setExpiry( self
::getAutoblockExpiry( $this->getTimestamp() ) );
971 $dbw = wfGetDB( DB_MASTER
);
972 $dbw->update( 'ipblocks',
974 'ipb_timestamp' => $dbw->timestamp( $this->getTimestamp() ),
975 'ipb_expiry' => $dbw->timestamp( $this->getExpiry() ),
978 'ipb_id' => $this->getId(),
986 * Get the IP address at the start of the range in Hex form
987 * @throws MWException
988 * @return string IP in Hex form
990 public function getRangeStart() {
991 switch ( $this->type
) {
992 case self
::TYPE_USER
:
995 return IP
::toHex( $this->target
);
996 case self
::TYPE_RANGE
:
997 list( $start, /*...*/ ) = IP
::parseRange( $this->target
);
1000 throw new MWException( "Block with invalid type" );
1005 * Get the IP address at the end of the range in Hex form
1006 * @throws MWException
1007 * @return string IP in Hex form
1009 public function getRangeEnd() {
1010 switch ( $this->type
) {
1011 case self
::TYPE_USER
:
1014 return IP
::toHex( $this->target
);
1015 case self
::TYPE_RANGE
:
1016 list( /*...*/, $end ) = IP
::parseRange( $this->target
);
1019 throw new MWException( "Block with invalid type" );
1026 public function getId() {
1033 * @param int $blockId
1036 private function setId( $blockId ) {
1037 $this->mId
= (int)$blockId;
1039 if ( is_array( $this->restrictions
) ) {
1040 $this->restrictions
= $this->getBlockRestrictionStore()->setBlockId(
1041 $blockId, $this->restrictions
1050 * @return int|null If this is an autoblock, ID of the parent block; otherwise null
1052 public function getParentBlockId() {
1053 return $this->mParentBlockId
;
1057 * Get/set a flag determining whether the master is used for reads
1059 * @param bool|null $x
1062 public function fromMaster( $x = null ) {
1063 return wfSetVar( $this->mFromMaster
, $x );
1067 * Get/set whether the block is a hardblock (affects logged-in users on a given IP/range)
1068 * @param bool|null $x
1071 public function isHardblock( $x = null ) {
1072 wfSetVar( $this->isHardblock
, $x );
1074 # You can't *not* hardblock a user
1075 return $this->getType() == self
::TYPE_USER
1077 : $this->isHardblock
;
1081 * @param null|bool $x
1084 public function isAutoblocking( $x = null ) {
1085 wfSetVar( $this->isAutoblocking
, $x );
1087 # You can't put an autoblock on an IP or range as we don't have any history to
1088 # look over to get more IPs from
1089 return $this->getType() == self
::TYPE_USER
1090 ?
$this->isAutoblocking
1095 * Get the block name, but with autoblocked IPs hidden as per standard privacy policy
1096 * @return string Text is escaped
1098 public function getRedactedName() {
1099 if ( $this->mAuto
) {
1100 return Html
::element(
1102 [ 'class' => 'mw-autoblockid' ],
1103 wfMessage( 'autoblockid', $this->mId
)->text()
1106 return htmlspecialchars( $this->getTarget() );
1111 * Get a timestamp of the expiry for autoblocks
1113 * @param string|int $timestamp
1116 public static function getAutoblockExpiry( $timestamp ) {
1117 global $wgAutoblockExpiry;
1119 return wfTimestamp( TS_MW
, wfTimestamp( TS_UNIX
, $timestamp ) +
$wgAutoblockExpiry );
1123 * Purge expired blocks from the ipblocks table
1125 public static function purgeExpired() {
1126 if ( wfReadOnly() ) {
1130 DeferredUpdates
::addUpdate( new AutoCommitUpdate(
1131 wfGetDB( DB_MASTER
),
1133 function ( IDatabase
$dbw, $fname ) {
1134 $ids = $dbw->selectFieldValues( 'ipblocks',
1136 [ 'ipb_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ],
1140 $blockRestrictionStore = MediaWikiServices
::getInstance()->getBlockRestrictionStore();
1141 $blockRestrictionStore->deleteByBlockId( $ids );
1143 $dbw->delete( 'ipblocks', [ 'ipb_id' => $ids ], $fname );
1150 * Given a target and the target's type, get an existing block object if possible.
1151 * @param string|User|int $specificTarget A block target, which may be one of several types:
1152 * * A user to block, in which case $target will be a User
1153 * * An IP to block, in which case $target will be a User generated by using
1154 * User::newFromName( $ip, false ) to turn off name validation
1155 * * An IP range, in which case $target will be a String "123.123.123.123/18" etc
1156 * * The ID of an existing block, in the format "#12345" (since pure numbers are valid
1158 * Calling this with a user, IP address or range will not select autoblocks, and will
1159 * only select a block where the targets match exactly (so looking for blocks on
1160 * 1.2.3.4 will not select 1.2.0.0/16 or even 1.2.3.4/32)
1161 * @param string|User|int|null $vagueTarget As above, but we will search for *any* block which
1162 * affects that target (so for an IP address, get ranges containing that IP; and also
1163 * get any relevant autoblocks). Leave empty or blank to skip IP-based lookups.
1164 * @param bool $fromMaster Whether to use the DB_MASTER database
1165 * @return DatabaseBlock|null (null if no relevant block could be found). The target and type
1166 * of the returned block will refer to the actual block which was found, which might
1167 * not be the same as the target you gave if you used $vagueTarget!
1169 public static function newFromTarget( $specificTarget, $vagueTarget = null, $fromMaster = false ) {
1170 $blocks = self
::newListFromTarget( $specificTarget, $vagueTarget, $fromMaster );
1171 return self
::chooseMostSpecificBlock( $blocks );
1175 * This is similar to DatabaseBlock::newFromTarget, but it returns all the relevant blocks.
1178 * @param string|User|int|null $specificTarget
1179 * @param string|User|int|null $vagueTarget
1180 * @param bool $fromMaster
1181 * @return DatabaseBlock[] Any relevant blocks
1183 public static function newListFromTarget(
1185 $vagueTarget = null,
1188 list( $target, $type ) = self
::parseTarget( $specificTarget );
1189 if ( $type == self
::TYPE_ID ||
$type == self
::TYPE_AUTO
) {
1190 $block = self
::newFromID( $target );
1191 return $block ?
[ $block ] : [];
1192 } elseif ( $target === null && $vagueTarget == '' ) {
1193 # We're not going to find anything useful here
1194 # Be aware that the == '' check is explicit, since empty values will be
1195 # passed by some callers (T31116)
1197 } elseif ( in_array(
1199 [ self
::TYPE_USER
, self
::TYPE_IP
, self
::TYPE_RANGE
, null ] )
1201 return self
::newLoad( $target, $type, $fromMaster, $vagueTarget );
1207 * Get all blocks that match any IP from an array of IP addresses
1209 * @param array $ipChain List of IPs (strings), usually retrieved from the
1210 * X-Forwarded-For header of the request
1211 * @param bool $isAnon Exclude anonymous-only blocks if false
1212 * @param bool $fromMaster Whether to query the master or replica DB
1213 * @return array Array of Blocks
1216 public static function getBlocksForIPList( array $ipChain, $isAnon, $fromMaster = false ) {
1217 if ( $ipChain === [] ) {
1222 $proxyLookup = MediaWikiServices
::getInstance()->getProxyLookup();
1223 foreach ( array_unique( $ipChain ) as $ipaddr ) {
1224 # Discard invalid IP addresses. Since XFF can be spoofed and we do not
1225 # necessarily trust the header given to us, make sure that we are only
1226 # checking for blocks on well-formatted IP addresses (IPv4 and IPv6).
1227 # Do not treat private IP spaces as special as it may be desirable for wikis
1228 # to block those IP ranges in order to stop misbehaving proxies that spoof XFF.
1229 if ( !IP
::isValid( $ipaddr ) ) {
1232 # Don't check trusted IPs (includes local CDNs which will be in every request)
1233 if ( $proxyLookup->isTrustedProxy( $ipaddr ) ) {
1236 # Check both the original IP (to check against single blocks), as well as build
1237 # the clause to check for rangeblocks for the given IP.
1238 $conds['ipb_address'][] = $ipaddr;
1239 $conds[] = self
::getRangeCond( IP
::toHex( $ipaddr ) );
1242 if ( $conds === [] ) {
1246 if ( $fromMaster ) {
1247 $db = wfGetDB( DB_MASTER
);
1249 $db = wfGetDB( DB_REPLICA
);
1251 $conds = $db->makeList( $conds, LIST_OR
);
1253 $conds = [ $conds, 'ipb_anon_only' => 0 ];
1255 $blockQuery = self
::getQueryInfo();
1256 $rows = $db->select(
1257 $blockQuery['tables'],
1258 array_merge( [ 'ipb_range_start', 'ipb_range_end' ], $blockQuery['fields'] ),
1262 $blockQuery['joins']
1266 foreach ( $rows as $row ) {
1267 $block = self
::newFromRow( $row );
1268 if ( !$block->isExpired() ) {
1277 * From a list of multiple blocks, find the most exact and strongest block.
1279 * The logic for finding the "best" block is:
1280 * - Blocks that match the block's target IP are preferred over ones in a range
1281 * - Hardblocks are chosen over softblocks that prevent account creation
1282 * - Softblocks that prevent account creation are chosen over other softblocks
1283 * - Other softblocks are chosen over autoblocks
1284 * - If there are multiple exact or range blocks at the same level, the one chosen
1286 * This should be used when $blocks were retrieved from the user's IP address
1287 * and $ipChain is populated from the same IP address information.
1289 * @param array $blocks Array of DatabaseBlock objects
1290 * @param array $ipChain List of IPs (strings). This is used to determine how "close"
1291 * a block is to the server, and if a block matches exactly, or is in a range.
1292 * The order is furthest from the server to nearest e.g., (Browser, proxy1, proxy2,
1294 * @throws MWException
1295 * @return DatabaseBlock|null The "best" block from the list
1297 public static function chooseBlock( array $blocks, array $ipChain ) {
1298 if ( $blocks === [] ) {
1300 } elseif ( count( $blocks ) == 1 ) {
1304 // Sort hard blocks before soft ones and secondarily sort blocks
1305 // that disable account creation before those that don't.
1306 usort( $blocks, function ( DatabaseBlock
$a, DatabaseBlock
$b ) {
1307 $aWeight = (int)$a->isHardblock() . (int)$a->appliesToRight( 'createaccount' );
1308 $bWeight = (int)$b->isHardblock() . (int)$b->appliesToRight( 'createaccount' );
1309 return strcmp( $bWeight, $aWeight ); // highest weight first
1312 $blocksListExact = [
1314 'disable_create' => false,
1318 $blocksListRange = [
1320 'disable_create' => false,
1324 $ipChain = array_reverse( $ipChain );
1326 foreach ( $blocks as $block ) {
1327 // Stop searching if we have already have a "better" block. This
1328 // is why the order of the blocks matters
1329 if ( !$block->isHardblock() && $blocksListExact['hard'] ) {
1331 } elseif ( !$block->appliesToRight( 'createaccount' ) && $blocksListExact['disable_create'] ) {
1335 foreach ( $ipChain as $checkip ) {
1336 $checkipHex = IP
::toHex( $checkip );
1337 if ( (string)$block->getTarget() === $checkip ) {
1338 if ( $block->isHardblock() ) {
1339 $blocksListExact['hard'] = $blocksListExact['hard'] ?
: $block;
1340 } elseif ( $block->appliesToRight( 'createaccount' ) ) {
1341 $blocksListExact['disable_create'] = $blocksListExact['disable_create'] ?
: $block;
1342 } elseif ( $block->mAuto
) {
1343 $blocksListExact['auto'] = $blocksListExact['auto'] ?
: $block;
1345 $blocksListExact['other'] = $blocksListExact['other'] ?
: $block;
1347 // We found closest exact match in the ip list, so go to the next block
1349 } elseif ( array_filter( $blocksListExact ) == []
1350 && $block->getRangeStart() <= $checkipHex
1351 && $block->getRangeEnd() >= $checkipHex
1353 if ( $block->isHardblock() ) {
1354 $blocksListRange['hard'] = $blocksListRange['hard'] ?
: $block;
1355 } elseif ( $block->appliesToRight( 'createaccount' ) ) {
1356 $blocksListRange['disable_create'] = $blocksListRange['disable_create'] ?
: $block;
1357 } elseif ( $block->mAuto
) {
1358 $blocksListRange['auto'] = $blocksListRange['auto'] ?
: $block;
1360 $blocksListRange['other'] = $blocksListRange['other'] ?
: $block;
1367 if ( array_filter( $blocksListExact ) == [] ) {
1368 $blocksList = &$blocksListRange;
1370 $blocksList = &$blocksListExact;
1373 $chosenBlock = null;
1374 if ( $blocksList['hard'] ) {
1375 $chosenBlock = $blocksList['hard'];
1376 } elseif ( $blocksList['disable_create'] ) {
1377 $chosenBlock = $blocksList['disable_create'];
1378 } elseif ( $blocksList['other'] ) {
1379 $chosenBlock = $blocksList['other'];
1380 } elseif ( $blocksList['auto'] ) {
1381 $chosenBlock = $blocksList['auto'];
1383 throw new MWException( "Proxy block found, but couldn't be classified." );
1386 return $chosenBlock;
1392 * Autoblocks have whichever type corresponds to their target, so to detect if a block is an
1393 * autoblock, we have to check the mAuto property instead.
1395 public function getType() {
1398 : parent
::getType();
1402 * Set the 'BlockID' cookie to this block's ID and expiry time. The cookie's expiry will be
1403 * the same as the block's, to a maximum of 24 hours.
1406 * @deprecated since 1.34 Set a cookie via BlockManager::trackBlockWithCookie instead.
1407 * @param WebResponse $response The response on which to set the cookie.
1409 public function setCookie( WebResponse
$response ) {
1410 MediaWikiServices
::getInstance()->getBlockManager()->setBlockCookie( $this, $response );
1414 * Unset the 'BlockID' cookie.
1417 * @deprecated since 1.34 Use BlockManager::clearBlockCookie instead
1418 * @param WebResponse $response The response on which to unset the cookie.
1420 public static function clearCookie( WebResponse
$response ) {
1421 MediaWikiServices
::getInstance()->getBlockManager()->clearBlockCookie( $response );
1425 * Get the BlockID cookie's value for this block. This is usually the block ID concatenated
1426 * with an HMAC in order to avoid spoofing (T152951), but if wgSecretKey is not set will just
1430 * @deprecated since 1.34 Use BlockManager::trackBlockWithCookie instead of calling this
1432 * @return string The block ID, probably concatenated with "!" and the HMAC.
1434 public function getCookieValue() {
1435 return MediaWikiServices
::getInstance()->getBlockManager()->getCookieValue( $this );
1439 * Get the stored ID from the 'BlockID' cookie. The cookie's value is usually a combination of
1440 * the ID and a HMAC (see DatabaseBlock::setCookie), but will sometimes only be the ID.
1443 * @deprecated since 1.34 Use BlockManager::getUserBlock instead
1444 * @param string $cookieValue The string in which to find the ID.
1445 * @return int|null The block ID, or null if the HMAC is present and invalid.
1447 public static function getIdFromCookieValue( $cookieValue ) {
1448 return MediaWikiServices
::getInstance()->getBlockManager()->getIdFromCookieValue( $cookieValue );
1454 * Build different messages for autoblocks and partial blocks.
1456 public function getPermissionsError( IContextSource
$context ) {
1457 $params = $this->getBlockErrorParams( $context );
1459 $msg = 'blockedtext';
1460 if ( $this->mAuto
) {
1461 $msg = 'autoblockedtext';
1462 } elseif ( !$this->isSitewide() ) {
1463 $msg = 'blockedtext-partial';
1466 array_unshift( $params, $msg );
1474 * Getting the restrictions will perform a database query if the restrictions
1475 * are not already loaded.
1478 * @return Restriction[]
1480 public function getRestrictions() {
1481 if ( $this->restrictions
=== null ) {
1482 // If the block id has not been set, then do not attempt to load the
1484 if ( !$this->mId
) {
1487 $this->restrictions
= $this->getBlockRestrictionStore()->loadByBlockId( $this->mId
);
1490 return $this->restrictions
;
1497 * @param Restriction[] $restrictions
1500 public function setRestrictions( array $restrictions ) {
1501 $this->restrictions
= array_filter( $restrictions, function ( $restriction ) {
1502 return $restriction instanceof Restriction
;
1511 public function appliesToTitle( Title
$title ) {
1512 if ( $this->isSitewide() ) {
1516 $restrictions = $this->getRestrictions();
1517 foreach ( $restrictions as $restriction ) {
1518 if ( $restriction->matches( $title ) ) {
1529 public function appliesToNamespace( $ns ) {
1530 if ( $this->isSitewide() ) {
1534 // Blocks do not apply to virtual namespaces.
1539 $restriction = $this->findRestriction( NamespaceRestriction
::TYPE
, $ns );
1541 return (bool)$restriction;
1547 public function appliesToPage( $pageId ) {
1548 if ( $this->isSitewide() ) {
1552 // If the pageId is not over zero, the block cannot apply to it.
1553 if ( $pageId <= 0 ) {
1557 $restriction = $this->findRestriction( PageRestriction
::TYPE
, $pageId );
1559 return (bool)$restriction;
1563 * Find Restriction by type and value.
1565 * @param string $type
1567 * @return Restriction|null
1569 private function findRestriction( $type, $value ) {
1570 $restrictions = $this->getRestrictions();
1571 foreach ( $restrictions as $restriction ) {
1572 if ( $restriction->getType() !== $type ) {
1576 if ( $restriction->getValue() === $value ) {
1577 return $restriction;
1585 * @deprecated since 1.34 Use BlockManager::trackBlockWithCookie instead of calling this
1589 public function shouldTrackWithCookie( $isAnon ) {
1590 wfDeprecated( __METHOD__
, '1.34' );
1591 $config = RequestContext
::getMain()->getConfig();
1592 switch ( $this->getType() ) {
1594 case self
::TYPE_RANGE
:
1595 return $isAnon && $config->get( 'CookieSetOnIpBlock' );
1596 case self
::TYPE_USER
:
1597 return !$isAnon && $config->get( 'CookieSetOnAutoblock' ) && $this->isAutoblocking();
1604 * Get a BlockRestrictionStore instance
1606 * @return BlockRestrictionStore
1608 private function getBlockRestrictionStore() : BlockRestrictionStore
{
1609 return MediaWikiServices
::getInstance()->getBlockRestrictionStore();
1614 * @deprecated since 1.34
1616 class_alias( DatabaseBlock
::class, 'Block' );